package org.jeecg.modules.flowable.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.flowable.entity.FlowInstance;
import org.jeecg.modules.flowable.entity.FlowInstanceParticipant;
import org.jeecg.modules.flowable.entity.FlowModelParticipant;
import org.jeecg.modules.flowable.enums.ParticipantUseScenariosEnum;
import org.jeecg.modules.flowable.mapper.FlowInstanceParticipantMapper;
import org.jeecg.modules.flowable.service.FlowInstanceParticipantService;
import org.jeecg.modules.flowable.service.FlowModelParticipantService;
import org.jeecg.modules.flowable.utils.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FlowInstanceParticipantServiceImpl extends ServiceImpl<FlowInstanceParticipantMapper, FlowInstanceParticipant> implements FlowInstanceParticipantService {

    final FlowModelParticipantService flowModelParticipantService;

    @Override
    public Result<Void> saveInstanceParticipant(FlowInstance instance) {
        String processInstanceId = instance.getId();
        String processInstanceName = instance.getName();
        String processDefinitionId = instance.getProcessDefinitionId();
        // 删除已有添加记录
        LambdaQueryWrapper<FlowInstanceParticipant> removeWrapper = Wrappers.lambdaQuery();
        removeWrapper.eq(FlowInstanceParticipant::getProcessInstanceId, processInstanceId);
        this.remove(removeWrapper);

        // 获取模型节点参与者列表
        List<FlowModelParticipant> modelParticipantList = this.flowModelParticipantService.queryByDefinitionIdAndUseScenarios(processDefinitionId, ParticipantUseScenariosEnum.APPROVE.getCode());

        List<FlowInstanceParticipant> instanceParticipantList = BeanUtils.convertListTo(modelParticipantList, FlowInstanceParticipant::new);

        instanceParticipantList.forEach(e -> {
            e.setId(IdUtil.fastSimpleUUID());
            e.setProcessInstanceId(processInstanceId);
            e.setProcessInstanceName(processInstanceName);
            e.setUseScenarios(ParticipantUseScenariosEnum.APPROVE.getCode());
        });

        this.saveBatch(instanceParticipantList);
        return Result.OK();
    }
}
